import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter } from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: ''
  }
}

const state = getDefaultState()

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {
    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  }
}

const actions = {
  // 登录
  async login({ commit }, userInfo) {
    try {
      const res = await login(userInfo)
      // console.log(res);
      setToken(res.data.token)
      commit('SET_TOKEN', res.data.token)
    } catch (error) {
      Message.error('登录失败')
    }
  },

  //获取用户信息
  async getInfo({ commit}) {
    try {
      const res = await getInfo()
      // console.log(res);
      commit('SET_NAME',res.data.name)
      commit('SET_AVATAR',res.data.avatar)
    } catch (error) {
      Message.error('登录过期，请重新登录')
    }
  },

  // 退出登录
  logout({ commit, state }) {
    return new Promise((resolve, reject) => {
      logout(state.token).then(() => {
        removeToken() // 必须先移除token
        resetRouter()
        commit('RESET_STATE')
        resolve()
      }).catch(error => {
        reject(error)
      })
    })
  },

  // 移除token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

const getters = {
  name: (state) => state.name
}

export default {
  namespaced: true,
  state,
  mutations,
  actions,
  getters
}

